﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.CMS.Workflow;
using MethodWorx.CMS.Plugins.ViewManagement;

namespace MethodWorx.CMS.TemplateParser.Installer.Components
{
    public class Views : IInstallationWorkflowComponent
    {
        public Workflow.StepExecutionResult Execute(Workflow.IWorkflowExecutionContext context, InstallerWorkflowComponentConfiguration configuration)
        {
            using (var uow = context.CmsDataProvider.GetUnitOfWorkFactory().Begin())
            {
                //
                //  ok, here we go
                var service = new StaticViewService(context.CmsDataProvider);

                foreach(var templateElement in configuration.ConfigurationElement.GetElements("View"))
                {
                    //
                    //  ok, this is a view
                    var contains = templateElement.GetAttributeValue("contains", "", true);
                    var name = templateElement.GetAttributeValue("name", "", true);

                    if (string.IsNullOrEmpty(contains))
                    {
                        return
                            Workflow.StepExecutionResult.Error(
                                "Invalid view workflow confiugration, 'Contains' is a required attribute, either Pages or ContentItems");
                    }

                    if (string.IsNullOrEmpty(name))
                    {
                        return
                            Workflow.StepExecutionResult.Error(
                                "Invalid view workflow confiugration, 'Name' is a required attribute.");
                    }

                    service.Create(new StaticView()
                                       {
                                           Pages = contains.ToLower() == "pages",
                                           ContentItems = contains.ToLower() == "contentitems",
                                           Ids = new Guid[0],
                                           Name = name
                                       });
                }

                uow.Commit();
            }
            return Workflow.StepExecutionResult.Ok();
            return StepExecutionResult.Ok();
        }
    }
}
